// domOperations.js

// 切换展示的无人机状态
function toggleDroneStatus() {
    document.querySelectorAll('.attackers, .scouts').forEach(function (span) {
        span.addEventListener('click', function () {
            document.querySelector('.attackers.selected')?.classList.remove('selected');
            document.querySelector('.scouts.selected')?.classList.remove('selected');
            this.classList.add('selected');
        });
    });
}

// DOM 加载完成后初始化仪表和饼图
function initOnDomContentLoaded() {
    initGauges();
    initPieChart();
}

// 绑定DOMContentLoaded事件
function bindDomContentLoaded() {
    document.addEventListener("DOMContentLoaded", function () {
        initOnDomContentLoaded();
        toggleDroneStatus();
    });
}

// 发起AJAX请求并处理响应，动态填充图片
document.addEventListener('DOMContentLoaded', function() {
    const modal = document.getElementById('imageDialog');
    const closeBtn = modal.querySelector('.close');

    // 关闭模态框
    closeBtn.onclick = () => modal.style.display = 'none';
    window.onclick = (event) => {
        if (event.target === modal) modal.style.display = 'none';
    };

    // 处理任务卡片点击
    document.querySelectorAll('.task-preview').forEach(card => {
        card.addEventListener('click', async function() {
            const taskId = this.dataset.taskId;
            modal.querySelector('.images-grid').innerHTML = '<div class="loading">加载中...</div>';
            modal.style.display = 'block';

            try {
                const response = await fetch(`/get-task-images/${taskId}/`);
                if (!response.ok) throw new Error('请求失败');
                const data = await response.json();
                displayImages(data.images);
            } catch (error) {
                modal.querySelector('.images-grid').innerHTML = `<div class="error">加载图片失败：${error.message}</div>`;
            }
        });
    });

    function displayImages(images) {
        const container = modal.querySelector('.images-grid');
        if (images.length === 0) {
            container.innerHTML = '<div class="no-images">该任务暂无图片</div>';
            return;
        }
        container.innerHTML = images.map(img =>
            `<img src="${img}" alt="任务图片" onerror="this.style.display='none'">`
        ).join('');
    }
});
